﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Common;
using C1.C1Excel;
using DAL;
using BLL;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;

using System.Text;
using System.EnterpriseServices;
using System.Configuration;
using App.Services;
using App.Views.ViewModels;

namespace App.Models
{
    //[SupportFilter]
    public class BaseController : Controller
    {
        public string GetCreatePerson()
        {
            if (Session["person"] != null)
            {
                SysPerson person = ((SysPerson)Session["person"]);
                if (person != null && string.IsNullOrWhiteSpace(person.Name))
                {
                    return person.Name;
                }
            }
            RedirectToAction("Account");
            
            return string.Empty;
        }
        protected override void OnException(ExceptionContext filterContext)
        {
            // 此处进行异常记录，可以记录到数据库或文本，也可以使用其他日志记录组件。
            // 通过filterContext.Exception来获取这个异常。

            LogClass log = new LogClass();
            log.WriteServiceLog(LogType.Exception, filterContext.Exception.Message, LogType.Exception,
                Result.Succeed, ConfigurationManager.AppSettings["ServiceId"]);//写入日志

            // 执行基类中的OnException
            //base.OnException(filterContext);

            // 重定向到异常显示页或执行其他异常处理方法
            //Response.Redirect("~/");
        }

        /// <summary>
        /// 获取字段，首选默认
        /// </summary>
        /// <returns></returns>
        //public List<SelectListItem> GetSysFields(string table, string colum)
        //{
        //    SysFieldsBLL sysFieldsRepository = new SysFieldsBLL();
        //    return sysFieldsRepository.GetSysFields(table, colum);

        //}
        /// <summary>
        /// 获取字段，首选默认
        /// </summary>
        /// <returns></returns>
        //public List<SelectListItem> GetSysFields(string table, string colum, string value)
        //{
        //    SysFieldsBLL sysFieldsRepository = new SysFieldsBLL();
        //    return sysFieldsRepository.GetSysFields(table, colum, value);
        //}
        public ILogClass log;
        public BaseController()
        { log = new LogClass(); }
        public string Prompt(string title, string message, string returnUrl, params object[] par)
        {
            if (string.IsNullOrEmpty(message))
            {
                message = "提示信息";
            }
            if (string.IsNullOrEmpty(title))
            {
                message = "提示信息";
            }
            return (@"     
        $('    <div id=@dialo@ title=@" + title + @"@>" + message + @"</div>').dialog({
                    autoOpen: true,
                    buttons: {
                        @继续操作@: function () {
                            $(this).dialog(@close@);
                        },
                        @返回列表@: function () {
                        window.location.href = @../../returnUrl@;
 
                            $(this).dialog(@close@);
                        }
                    }
                });    
      
     ").Replace('@', '"').Replace("returnUrl", returnUrl);
        }
        public string Prompt(string message)
        {
            return Prompt(message, message, "");

        }
        public string PromptEdit(string title, string message, string returnUrl, params object[] par)
        {
            if (string.IsNullOrEmpty(message))
            {
                message = "提示信息";
            }
            if (string.IsNullOrEmpty(title))
            {
                message = "提示信息";
            }
            return (@"    
            function callback(e,ui) {            
                  window.location.href = @../../returnUrl@;
            } 
            $('    <div id=@dialo@ title=@" + title + @"@>" + message + @"</div>').dialog({
                    autoOpen: true,
                    close:callback,
                    buttons: {                       
                        @返回列表@: function () {
                        window.location.href = @../../returnUrl@;
 
                            $(this).dialog(@close@);
                        }
                    }
                });    
      
     ").Replace('@', '"').Replace("returnUrl", returnUrl);
        }
        public string WriteExcleDaoChu(FlexigridParam param, dynamic[] query, int from = 1)
        {
            var names = param.QType.GetString().Split(',');
            var cols = param.Cols.GetString().Split(',');
            C1XLBook _book = new C1XLBook();
            string path = @"~/Content/b.xls";
            string xlsPath = System.Web.HttpContext.Current.Server.MapPath(path);
            _book.Load(xlsPath);
            string guid = "ltf" + Guid.NewGuid().ToString();
            string saveFileName = xlsPath.Path(guid);
            XLSheet sheet = _book.Sheets[0];
            XLCell cell = sheet[0, 0];
            Dictionary<string, string> propertyName;
            PropertyInfo[] properties;
            for (int i = 0; i < names.Length; i++)
            {
                cell = sheet[0, i];
                if (!string.IsNullOrWhiteSpace(names[i]))
                {
                    cell.Value = names[i]; //列值
                }
            }
            for (int i = 0; i < query.Length; i++)
            {
                propertyName = new Dictionary<string, string>();
                if (query[i] == null)
                {
                    continue;
                }
                Type type = query[i].GetType();
                properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (PropertyInfo property in properties)
                {
                    object o = property.GetValue(query[i], null);
                    if (!string.IsNullOrEmpty(property.Name) && o != null)
                    {
                        propertyName.Add(property.Name, o.ToString());
                    }
                }
                int j = 0;
                cols.All(a =>
                {
                    cell = sheet[i + from, j];
                    if (propertyName.ContainsKey(a)) //列名
                    {
                        cell.Value = propertyName[a]; //列值
                    }
                    j++;
                    return true;
                });
            }
            _book.Save(saveFileName);
            log.WriteServiceLog(LogType.Operation, string.Format("../../Files/{0}.xls", guid) + "，", "导出数据",
                Result.Succeed, ConfigurationManager.AppSettings["ServiceId"]);//写入日志
            return string.Format("../../Files/{0}.xls", guid); //path.Replace("b",guid);
        }
        public string WriteExcle(FlexigridParam param, dynamic[] query, int from = 1)
        {
            var names = param.QType.GetString().Split(',');
            var cols = param.Cols.GetString().Split(',');
            C1XLBook _book = new C1XLBook();
            string path = @"~/Files/b.xls";
            string xlsPath = System.Web.HttpContext.Current.Server.MapPath(path);
            _book.Load(xlsPath);
            string guid = Guid.NewGuid().ToString();
            string saveFileName = xlsPath.Path(guid);
            XLSheet sheet = _book.Sheets[0];
            XLCell cell = sheet[0, 0];
            Dictionary<string, string> propertyName;
            PropertyInfo[] properties;
            for (int i = 0; i < names.Length; i++)
            {
                cell = sheet[0, i];
                if (!string.IsNullOrWhiteSpace(names[i]))
                {
                    cell.Value = names[i]; //列值
                }
            }
            for (int i = 0; i < query.Length; i++)
            {
                propertyName = new Dictionary<string, string>();
                if (query[i] == null)
                {
                    continue;
                }
                Type type = query[i].GetType();
                properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (PropertyInfo property in properties)
                {
                    object o = property.GetValue(query[i], null);
                    if (!string.IsNullOrEmpty(property.Name) && o != null)
                    {
                        propertyName.Add(property.Name, o.ToString());
                    }
                }
                int j = 0;
                cols.All(a =>
                {
                    cell = sheet[i + from, j];
                    if (propertyName.ContainsKey(a)) //列名
                    {
                        cell.Value = propertyName[a]; //列值
                    }
                    j++;
                    return true;
                });
            }
            _book.Save(saveFileName);
            log.WriteServiceLog(LogType.Operation, string.Format("../../../Files/{0}.xls", guid) + "，", "导出数据",
                Result.Succeed, ConfigurationManager.AppSettings["ServiceId"]);//写入日志
            return string.Format("../../../Files/{0}.xls", guid); //path.Replace("b",guid);
        }
        public string WriteExcle2(FlexigridParam param, dynamic[] query, int from = 1)
        {
            var names = param.QType.GetString().Split(',');
            var cols = param.Cols.GetString().Split(',');
            C1XLBook _book = new C1XLBook();
            string path = @"~/Files/b.xls";
            string xlsPath = System.Web.HttpContext.Current.Server.MapPath(path);
            _book.Load(xlsPath);
            string guid = Guid.NewGuid().ToString();
            string saveFileName = xlsPath.Path(guid);
            XLSheet sheet = _book.Sheets[0];
            XLCell cell = sheet[0, 0];
            Dictionary<string, string> propertyName;
            PropertyInfo[] properties;
            for (int i = 0; i < names.Length; i++)
            {
                cell = sheet[0, i];
                if (!string.IsNullOrWhiteSpace(names[i]))
                {
                    cell.Value = names[i]; //列值
                }
            }
            for (int i = 0; i < query.Length; i++)
            {
                propertyName = new Dictionary<string, string>();
                if (query[i] == null)
                {
                    continue;
                }
                Type type = query[i].GetType();
                properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (PropertyInfo property in properties)
                {
                    object o = property.GetValue(query[i], null);
                    if (!string.IsNullOrEmpty(property.Name) && o != null)
                    {
                        propertyName.Add(property.Name, o.ToString());
                    }
                }
                int j = 0;
                cols.All(a =>
                {
                    cell = sheet[i + from, j];
                    if (propertyName.ContainsKey(a)) //列名
                    {
                        cell.Value = propertyName[a]; //列值
                    }
                    j++;
                    return true;
                });
            }
            _book.Save(saveFileName);
            log.WriteServiceLog(LogType.Operation, string.Format("../../Files/{0}.xls", guid) + "，", "导出数据",
                Result.Succeed, ConfigurationManager.AppSettings["ServiceId"]);//写入日志
            return string.Format("../../Files/{0}.xls", guid); //path.Replace("b",guid);
        }


        ////////////////////////////////////////////////////////////////////////////////////////
        //Ajax请求时返回成功的信息
        protected const string SUCCESS = "success";
        //Ajax请求删除的ID列表标识
        protected const string IDLIST = "idList";
        protected FuneralMisDBEntities dbe = null;
        protected override void Initialize(RequestContext requestContext)
        {
            if (dbe == null) dbe = new FuneralMisDBEntities();
            base.Initialize(requestContext);
        }

        protected string GoBack()
        {
            return "<a href='javascript:history.go(-1)'>返回</a>";
        }

        protected string CurrentUser
        {
            get
            {
                SysPerson personInfo = ((SysPerson)Session["person"]);
                if (personInfo == null)
                    return "";
                else
                    return personInfo.Name;
            }
        }

        protected string CurrentDeader
        {
            get { return "" + Session["DeadNO"]; }
            set { Session["DeadNO"] = value; }
        }

        //获取收费项目列表,将tb_ServicesItem转换为UCServicesItemListViewModel模型列表
        //serviceNO     收费主服务号
        //serviceType   服务类别
        public List<UCServicesItemListViewModel> GetServiceItemList(string serviceNO, string serviceType)
        {
            var list = dbe.tb_ServicesItem.
                    Where(m => m.ParentServiceID == serviceType).
                    Select(s => new UCServicesItemListViewModel
                    {
                        ItemNO = s.ItemNO,
                        ItemName = s.ItemName,
                        ItemLevel = s.ItemLevel,
                        Required = s.Required,
                        Unit = s.Unit,
                        Price = s.Price,
                        Qty = 1,
                        ParentServiceID = s.ParentServiceID,
                        ServiceContent = s.ServiceContent,
                        IsSelected = (s.Required != null && s.Required.Value) ? true : false
                    }).ToList();

            //如果是编辑，则还要获取相应的选择项目和数量
            foreach (var o in list)
            {
                var sd = dbe.tb_ServiceDetail.FirstOrDefault(m => m.ServiceNoParent == serviceNO && m.ItemNO == o.ItemNO);
                o.IsSelected = o.IsSelected ? o.IsSelected : sd != null;
                o.IsPay = sd == null ? false : sd.PayStatus;
                if (o.IsSelected && sd != null) o.Qty = sd.ServiceCount.Value;
            }
            return list;
        }

        //产生yyyyMMxxxx编号
        public string GenYYYYMMXXXX(string s)
        {
            string dt = string.Format("{0:yyyyMM}", DateTime.Now);
            if (s == null)
            {
                s = dt + "0001";
            }
            else
            {
                s = s.Substring(6);
                s = dt + string.Format("{0:0000}", int.Parse(s) + 1);
            }
            return s;
        }
        //自动生成服务编号
        public string GenServiceNo()
        {
            string dt = string.Format("{0:yyyyMM}", DateTime.Now);
            var s = dbe.tb_ServiceDetail.Where(m => m.ServiceNo.StartsWith(dt)).Select(m => m.ServiceNo).Max();
            return GenYYYYMMXXXX(s);
        }

        //自动生成用车编号
        public string GenUseVehicleNO()
        {
            string dt = string.Format("{0:yyyyMM}", DateTime.Now);
            var s = dbe.tb_UseVehicleRecords.Where(m => m.UseVehicleNO.StartsWith(dt)).Select(m => m.UseVehicleNO).Max();
            return GenYYYYMMXXXX(s);
        }
        //自动生成告别服务编号
        public string GenFarewellNO()
        {
            string dt = string.Format("{0:yyyyMM}", DateTime.Now);
            var s = dbe.tb_FarewellRecords.Where(m => m.FarewellNO.StartsWith(dt)).Select(m => m.FarewellNO).Max();
            return GenYYYYMMXXXX(s);
        }

        //自动生成火化服务编号
        public string GenCremationNO()
        {
            string dt = string.Format("{0:yyyyMM}", DateTime.Now);
            var s = dbe.tb_CremationRecords.Where(m => m.CremationNO.StartsWith(dt)).Select(m => m.CremationNO).Max();
            return GenYYYYMMXXXX(s);
        }
        

        //自动生成冷藏服务编号
        public string GenRefriNO()
        {
            string dt = string.Format("{0:yyyyMM}", DateTime.Now);
            var s = dbe.tb_RefriRecords.Where(m => m.RefriNO.StartsWith(dt)).Select(m => m.RefriNO).Max();
            return GenYYYYMMXXXX(s);
        }

        //自动生成死者编号
        public string GenDeadNO()
        {
            string dt = string.Format("{0:yyyyMM}", DateTime.Now);
            var s = dbe.tb_RegistrationInfo.Where(m => m.DeadNO.StartsWith(dt)).Select(m => m.DeadNO).Max();
            return GenYYYYMMXXXX(s);
        }
        //自动生成守灵服务编号
        public string GenWakeNO()
        {
            string dt = string.Format("{0:yyyyMM}", DateTime.Now);
            var s = dbe.tb_WakeRecords.Where(m => m.WakeNO.StartsWith(dt)).Select(m => m.WakeNO).Max();
            return GenYYYYMMXXXX(s);
        }

        //自动生成丧葬用品销售编号
        public string GenGoodsSaleNO()
        {
            string dt = string.Format("{0:yyyyMM}", DateTime.Now);
            var s = dbe.tb_GoodsSaleRecords.Where(m => m.SaleNO.StartsWith(dt)).Select(m => m.SaleNO).Max();
            return GenYYYYMMXXXX(s);
        }

        //自动生成整理服务编号
        public string GenCosmeticNO()
        {
            string dt = string.Format("{0:yyyyMM}", DateTime.Now);
            var s = dbe.tb_CosmeticRecords.Where(m => m.CosmeticNO.StartsWith(dt)).Select(m => m.CosmeticNO).Max();
            return GenYYYYMMXXXX(s);
        }

        //添加选择的服务收费明细
        //datalist: id,qty,subtotal|id,qty,..
        public void AddServiceItems(string deadNO, string serviceNO, string datalist)
        {
            string[] items = datalist.Split('|');
            bool isFirst = true;
            int serviceno = int.Parse(serviceNO);
            foreach (var item in items)
            {
                string[] strs = item.Split(',');
                var sd = new tb_ServiceDetail
                {
                    DeadNO = deadNO,
                    ServiceNo = isFirst ? serviceNO : "" + (++serviceno),
                    ServiceNoParent = serviceNO,
                    ItemNO = strs[0],
                    ServiceCount = int.Parse(strs[1]),
                    ServiceCountBak = int.Parse(strs[1]),
                    ServiceFee = decimal.Parse(strs[2]),
                    ApplyTime = DateTime.Now,
                    Salesman = CurrentUser
                };
                isFirst = false;
                dbe.tb_ServiceDetail.AddObject(sd);
            }
        }

        //修改选择的服务费用明细
        public void EditServiceItems(string datalist, string deadNO, string serviceNO)
        {
            var oldItemNOs = dbe.tb_ServiceDetail.Where(m => m.ServiceNoParent == serviceNO).Select(m => m.ItemNO).ToList();
            string[] items = datalist.Split('|');
            int serviceno = int.Parse(GenServiceNo());
            foreach (var item in items)
            {
                string[] strs = item.Split(',');
                string itemNO = strs[0];
                if (oldItemNOs.Contains(itemNO)) oldItemNOs.Remove(itemNO);
                var sd = dbe.tb_ServiceDetail.FirstOrDefault(m => m.ServiceNoParent == serviceNO && m.ItemNO == itemNO);
                //新选的收费
                if (sd == null)
                {
                    sd = new tb_ServiceDetail
                    {
                        DeadNO = deadNO,
                        ServiceNo = "" + serviceno,
                        ServiceNoParent = serviceNO,
                        ItemNO = strs[0],
                        ServiceCount = int.Parse(strs[1]),
                        ServiceCountBak = int.Parse(strs[1]),
                        ServiceFee = decimal.Parse(strs[2]),
                        ApplyTime = DateTime.Now,
                        Salesman = CurrentUser
                    };
                    dbe.tb_ServiceDetail.AddObject(sd);
                    serviceno++;
                }
                else
                {
                    sd.ItemNO = strs[0];
                    sd.DeadNO = deadNO;
                    sd.ServiceCount = int.Parse(strs[1]);
                    sd.ServiceFee = decimal.Parse(strs[2]);
                }
            }
            //对于去除的费用，在这里删除，将来需要做日志记录，否则会出现编号不连续的情况
            foreach (var item in oldItemNOs)
            {
                var sd = dbe.tb_ServiceDetail.FirstOrDefault(m => m.ServiceNoParent == serviceNO && m.ItemNO == item);
                dbe.tb_ServiceDetail.DeleteObject(sd);
            }
        }

        //删除服务收费
        public void DeleteServiceItems(string serviceNO)
        {
            var sds = dbe.tb_ServiceDetail.Where(m => m.ServiceNoParent == serviceNO);
            foreach (var sd in sds)
            {
                dbe.tb_ServiceDetail.DeleteObject(sd);
            }
        }

    }
}